<script setup lang="ts">
  import { ref, createVNode } from 'vue';
  import dayjs from 'dayjs';
  import { BasicTable, useTable, TableAction, TableImg } from '@/components/Table';
  import {
    getCollectionIndexApi,
    getCollectionApi,
    EditCollectionApi,
    DeleteCollectionApi,
    EditCollectionArrayApi,
  } from '@/api/collection';
  import { Tag } from '@/components/InfoTag';
  import { CollectionInfoModal, EditPaymentModal, AddPaymentModal } from './modal';
  import { useModal } from '@/components/Modal';
  import message from '../form-design/utils/message';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

  const info = ref({
    total: 0,
  });
  const state = ref({
    selectedRowKeys: [],
  });

  const onSelectChange = (e) => {
    console.log(e);
  };

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerEditModal, { openModal: openEditModal }] = useModal();
  const [registerAddModal, { openModal: openAddModal }] = useModal();

  const [registerTable, { getRawDataSource, reload, getSelectRowKeys }] = useTable({
    title: '收款信息',
    canResize: true,
    columns: [
      {
        title: '通道类型',
        dataIndex: 'title',
        resizable: true,
      },
      {
        title: '接单状态',
        dataIndex: 'status',
        resizable: true,
      },
      {
        title: '收款信息',
        align: 'left',
        dataIndex: 'input',
        resizable: true,
      },
      {
        title: '操作类型',
        dataIndex: 'type',
        resizable: true,
      },
      {
        title: '固码金额',
        dataIndex: 'regularNumber',
        resizable: true,
      },
      {
        title: '成单率',
        dataIndex: 'successInfo',
        resizable: true,
      },
      {
        title: '单日限单',
        dataIndex: 'limitNumber',
        resizable: true,
      },
      {
        title: '单日限额',
        dataIndex: 'limitMoney',
        resizable: true,
      },
      {
        title: '二维码',
        dataIndex: 'agentImgSrc',
        resizable: true,
      },
      {
        title: '最后开启时间',
        dataIndex: 'update_time',
        resizable: true,
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        resizable: true,
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 200,
        fixed: 'right',
      },
    ],
    bordered: true,
    showSelectionBar: false,
    showTableSetting: true,
    accordion: true, // 手风琴效果
    api: getCollectionIndexApi,
    fetchSetting: {
      listField: 'list',
    },
    afterFetch: () => {
      const data = getRawDataSource();
      info.value.total = data.total;
    },
    useSearchForm: true,
    formConfig: {
      labelWidth: 120,
      schemas: [
        {
          field: 'code',
          label: '通道类型',
          component: 'ApiSelect',
          colProps: {
            span: 6,
          },
          componentProps: {
            api: getCollectionApi,
            resultField: 'list',
            labelField: 'title',
            valueField: 'ball.code',
          },
        },
        {
          field: 'status',
          label: '接单状态',
          component: 'Select',
          colProps: {
            span: 6,
          },
          componentProps: {
            options: [
              {
                label: '全部状态',
                value: '',
              },
              {
                label: '开启',
                value: '1',
              },
              {
                label: '关闭',
                value: '0',
              },
            ],
          },
        },
        {
          field: 'type',
          label: '操作类型',
          component: 'Select',
          colProps: {
            span: 6,
          },
          componentProps: {
            options: [
              {
                label: '全部分类',
                value: '',
              },
              {
                label: '手动',
                value: '0',
              },
              {
                label: '自动',
                value: '1',
              },
            ],
          },
        },
        {
          field: 'orderNo',
          label: '收款账号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'input',
          label: '收款姓名',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
      ],
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: state.value.selectedRowKeys,
      onChange: onSelectChange,
    },
    clickToRowSelect: false,
    takeCare: '这是注意事项',
  });

  const handleDel = (data) => {
    Modal.confirm({
      title: '删除确认',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确定要删除 “${data.title}” 通道吗？`,
      onOk() {
        DeleteCollectionApi({ ids: [data.id] }).then(() => {
          message.success('删除成功');
          reload();
        });
      },
    });
  };

  const handleEdit = (data) => {
    openEditModal(true, { id: data.code, name: data.title, record: data });
  };

  const reloadTable = () => {
    setTimeout(() => {
      reload();
    }, 1500);
  };

  const onChangeStatus = async (record) => {
    try {
      await EditCollectionApi({ id: record.id, status: record.status });
      message.success('更新成功');
    } catch (error) {
      message.error(error);
    }
  };

  function formatInput(info) {
    let text = '';
    info.forEach((element) => {
      text += element.title + ':' + element.value + '<br/>';
    });
    return text;
  }

  function ChangeStatus(value) {
    const ids = getSelectRowKeys();
    const params = {
      ids: ids,
      status: value,
    };
    EditCollectionArrayApi(params).then(() => {
      message.success('更新成功');
      reload();
    });
  }

  function DeleteCollection() {
    const ids = getSelectRowKeys();
    Modal.confirm({
      title: '删除确认',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确定要删除 全部 通道吗？`,
      onOk() {
        DeleteCollectionApi({ ids }).then(() => {
          message.success('删除成功');
          reload();
        });
      },
    });
  }
</script>
<template>
  <main>
    <a-row :gutter="16">
      <a-col :span="24" style="margin-top: 16px">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <a-button size="small" type="primary" @click="openAddModal(true)"
              >添加收款信息</a-button
            >
            <a-button size="small" @click="ChangeStatus(1)">批量开启接单</a-button>
            <a-button size="small" @click="ChangeStatus(0)">批量关闭接单</a-button>
            <a-button size="small" @click="DeleteCollection">批量删除</a-button>
            <Tag title="收款信息数量" color="green">{{ info.total }}</Tag>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'create_time'">
              {{ dayjs(record.create_time * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-if="column.key === 'update_time'">
              {{ dayjs(record.update_time * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-if="column.key === 'type'">{{
              record.type === '0' ? '手动' : record.type === '1' ? '自动' : '第三方'
            }}</template>
            <template v-if="column.key === 'status'">
              <a-switch
                v-model:checked="record.status"
                :checkedValue="'1'"
                :unCheckedValue="'0'"
                @click="onChangeStatus(record)"
              />
            </template>
            <template v-if="column.dataIndex == 'input'">
              <div
                style="text-align: left"
                v-html="record.input ? formatInput(record?.input) : ''"
              ></div>
            </template>
            <template v-if="column.key === 'successInfo'">
              <a-button type="primary" size="small" danger @click="openModal(true, record)"
                >查看</a-button
              >
            </template>
            <template v-if="column.key === 'agentImgSrc'">
              <TableImg :img-list="[record.agentImgSrc]" simpleShow />
            </template>
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '修改',
                    type: 'default',
                    onClick: handleEdit.bind(null, record),
                  },
                  {
                    label: '删除',
                    type: 'primary',
                    onClick: handleDel.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable>
      </a-col>
    </a-row>

    <CollectionInfoModal @register="registerModal" @ok="closeModal" />
    <AddPaymentModal @register="registerAddModal" @ok="reloadTable" />
    <EditPaymentModal @register="registerEditModal" @ok="reloadTable" />
  </main>
</template>
